package com.ftwj.demo.modular.service;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.ftwj.demo.base.common.BaseService;
import com.ftwj.demo.modular.vo.dao.ExcelMessageVoDao;
import com.ftwj.demo.modular.vo.entity.ExcelMessageVo;
import com.ftwj.demo.modular.vo.entity.ExcelUserVo;
import com.ftwj.demo.permission.dao.UserDao;
import com.ftwj.demo.utils.excel.ExcelTypeEnum;
import com.ftwj.demo.utils.excel.ExcelUtils;
import com.ftwj.demo.utils.logs.LoggerUtil;

import cn.afterturn.easypoi.csv.CsvImportUtil;
import cn.afterturn.easypoi.csv.entity.CsvImportParams;
import cn.afterturn.easypoi.handler.inter.IReadHandler;

/**
* <p>Title: ExcelService</p>  
* <p>Description: excel业务逻辑层</p>
* <p>Copyright: Copyright (c) 2020 </p>  
* <p>Company: 兰州飞天网景信息产业有限公司</p>    
* @author HeYang
* @date 2020年4月21日 下午6:18:52
* @version V1.0
 */
@Service
public class ExcelService extends BaseService<ExcelUserVo, Integer>{
	
	@Value("${file.excelTempPath}")
	private String excelTempPath;//
	@Value("${file.userComplexTemplate}")
	private String userComplexTemplate;
	@Autowired
	private ExcelMessageVoDao messageVoDao;
	@Autowired
	private UserDao userDao;

	/**
	 * <p>Title: exportExcel</p>  
	 * <p>Description: 无模板导出</p>  
	 * @param response 
	 * @author HeYang
	 * @date 2020年4月21日  
	 * @version 1.0
	 */
	public void exportExcel(HttpServletResponse response) {
		long start = System.currentTimeMillis();
	    List<ExcelUserVo> list = this.findListByExample(new ExcelUserVo());
	    try {
//			ExcelUtils.exportExcel(list, "员工信息表", "员工信息", UserExcelVo.class, "员工信息", response);
			ExcelUtils.exportExcel(response,"员工信息表","员工信息表",list, ExcelUserVo.class,ExcelTypeEnum.XLS);
			LoggerUtil.info("导出excel所花时间：" + (System.currentTimeMillis() - start));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * <p>Title: importExcel</p>  
	 * <p>Description: 无模板导入</p>  小数据量导入，万级以下  测试 五十万数据   大约37秒
	 * @param file 
	 * @author HeYang
	 * @date 2020年4月21日  
	 * @version 1.0
	 */
	public void importExcel(MultipartFile file) {
		long start = System.currentTimeMillis();
	    List<ExcelUserVo> personVoList = new ArrayList<>();
	    LoggerUtil.info("excel导入开始");
		try {
			personVoList = ExcelUtils.importExcel(file,1,1, ExcelUserVo.class);
		} catch (Exception e) {
			e.printStackTrace();
		}
	    LoggerUtil.info("导入excel所花时间：" + (System.currentTimeMillis() - start)+"  测试条数：" + personVoList.size());
	}

	/**
	 * <p>Title: exportExcel</p>  
	 * <p>Description: 模板导出</p>  
	 * @param response
	 * @param excelName
	 * @param templatePath 获取导出excel指定模版
	 * @author HeYang
	 * @date 2020年4月21日  
	 */
	public boolean exportExcel(HttpServletResponse response,HttpServletRequest request,String excelName) {
        // 查询数据,此处查出List<Map> 和 List<Pojo> 均可
    	List<ExcelUserVo> list = this.findListByExample(new ExcelUserVo());
//    	List<Map<String, Object>> list = this.findListMapByExample(new UserExcelVo());
    	String templatePath = "D:\\mytest\\easypoiExample.xls";//此处地址可以从配置文件获取
        ExcelUtils.templateListExport(response,request,list,templatePath,excelName);
        return true;
	}

	/**
	 * <p>Title: excelToHtml</p>  
	 * <p>Description: excel转html</p>  
	 * @param response
	 * @param path 
	 * @author HeYang
	 * @date 2020年4月21日  
	 * @version 1.0
	 */
	public void excelToHtml(HttpServletResponse response,String path) {
		ExcelUtils.excelToHtml(response,path);
	}

	/**
	 * <p>Title: wordExport</p>  
	 * <p>Description: word导出</p>  
	 * @param response
	 * @param path 
	 * @author HeYang
	 * @date 2020年4月21日  
	 * @version 1.0
	 */
	public void wordExport(HttpServletRequest request,HttpServletResponse response) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		//假数据
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> list = new ArrayList<>();
		for (int i=0; i< 10 ;i++) {
			Map<String, Object> map2 = new HashMap<>();
			map2.put("title", "标题"+i);
			map2.put("answer", "答案"+i);
			list.add(map2);
		}
        map.put("department", "Easypoi");
        map.put("person", "JueYue");
        map.put("phone", "17361685895");
        map.put("time1", format.format(new Date()));
        map.put("list", list);
        
        String templatePath = "D:/mytest/word.docx";
        String temDir = "D:/mytest/";
        String fileName = "员工信息表WORD.docx";
        try {
            ExcelUtils.exportWord(request,response,templatePath,temDir,fileName,map);
        } catch (Exception e) {
            e.printStackTrace();
        }
	}

	/**
	 * <p>Title: cvsExport</p>  
	 * <p>Description: 导出CVS</p>  
	 * @param request
	 * @param response 
	 * @author HeYang
	 * @date 2020年4月22日
	 * @version 1.0
	 */
	public void cvsExport(HttpServletRequest request, HttpServletResponse response) {
        List<ExcelUserVo> list = new ArrayList<ExcelUserVo>();
        Date start = new Date();
        
        for (int i = 0; i < 500000; i++) {
        	ExcelUserVo user = new ExcelUserVo();
        	user.setShowName(i+"");
        	user.setLoginName("何洋"+i);
        	user.setPhone("17797651234");
        	user.setCreateTime(new Date());
            list.add(user);
        }
        String catalog = "D:/mytest/";
        String fileName = "cvs数据.csv";
        ExcelUtils.exportCvs(list, ExcelUserVo.class, catalog, fileName);
        LoggerUtil.info("导出完成" + (new Date().getTime() - start.getTime()));
	}

	/**
	 * <p>Title: complexExport</p>  
	 * <p>Description: 复杂导出</p>  
	 * @param request
	 * @param response 
	 * @author HeYang
	 * @date 2020年4月22日  
	 * @version 1.0
	 */
	public void complexExport(HttpServletRequest request, HttpServletResponse response) {
		long start = System.currentTimeMillis();
		List<ExcelMessageVo> vos = new ArrayList<>();
		List<Map<String, Object>> list = messageVoDao.queryMessAndReceive();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-M-dd HH:mm:ss"); 
		 try {
			for (Map<String, Object> map : list) {
				ExcelMessageVo vo = new ExcelMessageVo();
				vo.setTitle(map.get("title").toString());
				vo.setContent(map.get("content").toString());
				vo.setCreateUser(map.get("createUser").toString());
				vo.setReceiveUser(map.get("receiveUser").toString());
				vo.setUpdateTime(format.parse(map.get("updateTime").toString()));
				vos.add(vo);
			}
			ExcelUtils.exportExcel(response,"消息发送表", "消息发送信息",vos,ExcelMessageVo.class,ExcelTypeEnum.XLS);
			LoggerUtil.info("导出excel所花时间：" + (System.currentTimeMillis() - start));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * <p>Title: bigDateInport</p>  
	 * <p>Description: excel大数据cvs导入</p>  测试500,000 五十万条数据  25,532秒
	 * @param file 
	 * @author HeYang
	 * @date 2020年4月23日  
	 * @version 1.0
	 */
	public void bigDateImport(MultipartFile file) {
		try {
			InputStream inputstream = file.getInputStream();
			CsvImportParams params = new CsvImportParams(CsvImportParams.GBK);
			LoggerUtil.info("----cvs导入开始------");
			long start = System.currentTimeMillis();
//			List<UserExcelVo> list =      //两种方式，1参数中去除IReadHandler 可以用list<Bean>接收    2，参数中加上IReadHandler，无返回值
			CsvImportUtil.importCsv(inputstream, ExcelUserVo.class, params,new IReadHandler<ExcelUserVo>() {

				@Override
				public void handler(ExcelUserVo t) {
//					LoggerUtil.info(toString().toString());//数据输出，这样更快 这里可以写保存数据库的逻辑
				}

				@Override
				public void doAfterAll() {
					LoggerUtil.info("结束");//结束标识
				}
			});
			LoggerUtil.info("---------"+(System.currentTimeMillis()-start));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * <p>Title: userComplexExport</p>  
	 * <p>Description: 描述</p>  
	 * @param request
	 * @param response
	 * @param excelName 
	 * @author HeYang
	 * @date 2020年4月26日  
	 * @version 1.0
	 */
	public void userComplexExport(HttpServletRequest request, HttpServletResponse response,String excelName,String name,String phone,String card
			,String gender,String address,String area,String dept) {
		List<Map<String, Object>> list = userDao.queryUserAndInfo(name,phone,card,gender,address,area,dept);
		ExcelUtils.templateListExport(response,request, list, userComplexTemplate,excelName);
	}
	
}
